package cn.edu.hstc.wm.ui;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.graphics.Point;
import android.os.Build;
import android.text.format.DateFormat;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.webkit.WebView;
import cn.edu.hstc.wm.AppApplication;
import cn.edu.hstc.wm.R;

/**
 * 显示日志变更的类
 */
public class ChangeLogDialog {
	private static final String TAG = "ChangeLogDialog";

	private final Context mContext;

	private static ChangeLogDialog sDialog = null;

	private AlertDialog.Builder mBuilder = null;

	private AlertDialog mDialog = null;

	// 默认样式
	private String mStyle = "h1 { margin-left: 0px; font-size: 12pt; }" + "li { margin-left: 0px; font-size: 9pt; }" + "ul { padding-left: 30px; }"
			+ ".summary { font-size: 9pt; color: #606060; display: block; clear: left; }" + ".date { font-size: 9pt; color: #606060;  display: block; }";

	protected DialogInterface.OnDismissListener mOnDismissListener;

	/**
	 * 单例模式,获取实例
	 */
	public static ChangeLogDialog getInstance(Context context) {
		if (sDialog == null) {
			sDialog = new ChangeLogDialog(context);
		}
		Log.d(TAG, "getInstance  " + sDialog.toString());
		return sDialog;
	}

	// 私有构造函数
	private ChangeLogDialog(Context context) {
		mContext = context;
	}

	protected Context getContext() {
		return mContext;
	}

	// 格式化日期
	@SuppressLint("SimpleDateFormat")
	private String parseDate(final String dateString) {
		final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
		try {
			final Date parsedDate = dateFormat.parse(dateString);
			return DateFormat.getDateFormat(getContext()).format(parsedDate);
		} catch (ParseException ignored) {
			return dateString;
		}
	}

	// 解析xml数据
	private void parseReleaseTag(final StringBuilder changelogBuilder, final XmlPullParser resourceParser) throws XmlPullParserException, IOException {
		changelogBuilder.append("<h1>Release: ").append(resourceParser.getAttributeValue(null, "version")).append("</h1>");

		// 添加时间
		if (resourceParser.getAttributeValue(null, "date") != null) {
			changelogBuilder.append("<span class='date'>").append(parseDate(resourceParser.getAttributeValue(null, "date"))).append("</span>");
		}

		// 添加小标题
		if (resourceParser.getAttributeValue(null, "summary") != null) {
			changelogBuilder.append("<span class='summary'>").append(resourceParser.getAttributeValue(null, "summary")).append("</span>");
		}

		changelogBuilder.append("<ul>");

		// 解析子节点,更新信息
		int eventType = resourceParser.getEventType();
		while ((eventType != XmlPullParser.END_TAG) || (resourceParser.getName().equals("change"))) {
			if ((eventType == XmlPullParser.START_TAG) && (resourceParser.getName().equals("change"))) {
				eventType = resourceParser.next();
				changelogBuilder.append("<li>" + resourceParser.getText() + "</li>");
			}
			eventType = resourceParser.next();
		}
		changelogBuilder.append("</ul>");
	}

	// css样式
	private String getStyle() {
		return String.format("<style type=\"text/css\">%s</style>", mStyle);
	}

	// 设置样式
	public void setStyle(final String style) {
		mStyle = style;
	}

	public ChangeLogDialog setOnDismissListener(final DialogInterface.OnDismissListener onDismissListener) {
		mOnDismissListener = onDismissListener;
		return this;
	}

	/**
	 * 获取THML文本
	 * 
	 * @param resourceId
	 *            xml 资源文件
	 * @param resources
	 * @param version
	 *            需要解析的版本号,0表示解析所有的
	 * @return
	 */
	private String getHTMLChangelog(final int resourceId, final Resources resources, final int version) {
		boolean releaseFound = false;
		final StringBuilder changelogBuilder = new StringBuilder();
		changelogBuilder.append("<html><head>").append(getStyle()).append("</head><body>"); // 添加样式
		final XmlResourceParser xmlParser = resources.getXml(resourceId);
		try {
			int eventType = xmlParser.getEventType();
			while (eventType != XmlPullParser.END_DOCUMENT) {
				if ((eventType == XmlPullParser.START_TAG) && (xmlParser.getName().equals("release"))) {
					// 检查版本号是否有,当version=0时解析所有的
					final int versioncode = Integer.parseInt(xmlParser.getAttributeValue(null, "versioncode"));
					if ((version == 0) || (versioncode == version)) {
						parseReleaseTag(changelogBuilder, xmlParser);
						releaseFound = true;
					}
				}
				eventType = xmlParser.next();
			}
		} catch (XmlPullParserException e) {
			Log.e(TAG, e.getMessage(), e);
			return "";
		} catch (IOException e) {
			Log.e(TAG, e.getMessage(), e);
			return "";
		} finally {
			xmlParser.close();
		}
		changelogBuilder.append("</body></html>");
		// 找到发行版本号标记
		if (releaseFound) {
			return changelogBuilder.toString();
		} else {
			return "";
		}
	}

	// 获取文本内容以HTML返回
	public String getHTML() {
		final String packageName = mContext.getPackageName();
		final Resources resources;
		try {
			// resources = mContext.getResources();
			resources = mContext.getPackageManager().getResourcesForApplication(packageName);
		} catch (NameNotFoundException ignored) {
			return "";
		}

		return getHTMLChangelog(R.xml.changelog, resources, 0);
	}

	// 显示
	public void show() {
		show(0);
	}

	protected void show(final int version) {
		// final String packageName = mContext.getPackageName();
		final Resources resources;
		// try {
		// resources =
		// mContext.getPackageManager().getResourcesForApplication(packageName);
		// } catch (NameNotFoundException ignored) {
		// return;
		// }

		resources = mContext.getResources();
		// dialog title
		String title = resources.getString(R.string.change_log_title);
		title = String.format("%s %s", title, ((AppApplication) mContext.getApplicationContext()).getVersionName());

		// change log
		final String htmlChangelog = getHTMLChangelog(R.xml.changelog, resources, version);

		// 关闭
		final String closeString = resources.getString(R.string.changelog_close);

		// 日志记录不为空
		if (htmlChangelog.length() == 0) {
			return;
		}

		// 创建WebView来加载HTML文本
		final WebView webView = new WebView(mContext);
		webView.loadDataWithBaseURL(null, htmlChangelog, "text/html", "utf-8", null);
		mBuilder = new AlertDialog.Builder(mContext).setTitle(title).setView(webView).setPositiveButton(closeString, new Dialog.OnClickListener() {
			public void onClick(final DialogInterface dialogInterface, final int i) {
				dialogInterface.dismiss();
			}
		}).setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				dialog.dismiss();
			}
		});
		mDialog = mBuilder.create();
		initDialog();
		// mDialog.setCanceledOnTouchOutside(true);
		// window.setBackgroundDrawableResource(R.color.transparent);
		mDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
			@Override
			public void onDismiss(final DialogInterface dialog) {
				if (mOnDismissListener != null) {
					mOnDismissListener.onDismiss(dialog);
				}
			}
		});

		mDialog.show();
		// builder.show();
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	@SuppressWarnings("deprecation")
	private void initDialog() {
		if (mDialog != null) {
			int fullWidth = mDialog.getWindow().getAttributes().width;

			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
				Display display = ((Activity) mContext).getWindowManager().getDefaultDisplay();
				Point size = new Point();
				display.getSize(size);
				fullWidth = size.x;
			} else {
				Display display = ((Activity) mContext).getWindowManager().getDefaultDisplay();
				fullWidth = display.getWidth();
			}

			final int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, mContext.getResources().getDisplayMetrics());

			int w = fullWidth - padding;
			int h = mDialog.getWindow().getAttributes().height;

			mDialog.getWindow().setLayout(w, h); // 设置位置
			mDialog.setCanceledOnTouchOutside(true); // 触摸边界外取消
			mDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
		}
	}
}
